﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace WDA.Core.DynamicReconfiguration
{   
   internal sealed class ConfigurationLockProxyInterceptor : ICallHandler
   {      
		private readonly long _version;

      [Dependency(WDAContainerNames.PersistentInternalContainerName)]
      public IUnityContainer Container { get; set; }

		public ConfigurationLockProxyInterceptor(long version)
		{
			_version = version;
		}
      
      #region ICallHandler Members
      public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
      {         
         ReaderWriterLockSlim configLock = Container.Resolve<ReaderWriterLockSlim>();
         try
         {
            configLock.EnterReadLock();
            RuntimeVersion v = Container.Resolve<RuntimeVersion>();
            if (v.VersionNumber != _version)
            {
               throw new InvalidOperationException("Proxy liftime expired.");
            }
            return getNext()(input, getNext);            
         }
         finally
         {
            configLock.ExitReadLock();
         }
      }
      public int Order
      {
         get
         {
            return 1;
         }
         set
         {          
            throw new NotSupportedException();
         }
      }
      #endregion
   }
}
